<template>
  <div>
    <a-range-picker
      :inputReadOnly="inputReadOnly"
      :disabled="disabled || readOnly"
      :placeholder="placeholder"
      :format="dateFormat"
      :valueFormat="dateFormat"
      :disabled-date="disabledDate"
      :isDisableDateRange="isDisableDateRange"
      v-bind="$attrs"
      :value="dateRange"
      :defaultValue="defaultValues"
      :allowClear="allowClear"
      :ranges="ranges"
      :showTime="showTime"
      @calendarChange="calendarChange"
      @change="change"
      @ok="handleOk"
      @openChange="openChange"
      @panelChange="handlePanelChange"
    />
  </div>
</template>
<script>
import moment from 'moment'
export default {
  name: 'JRangePicker',
  props: {
    placeholder: {
      type: Array,
      default: () => ['开始日期', '结束日期'],
      required: false,
    },
    beginDate: {
      //开始日期
      type: String,
      default: '',
    },
    endDate: {
      //结束日期
      type: String,
      default: '',
    },
    value: {
      type: String,
      required: false,
    },
    dateFormat: {
      type: String,
      default: 'YYYY-MM-DD HH:mm:ss',
    },
    readOnly: {
      type: Boolean,
      required: false,
      default: false,
    },
    isExportAll: {
      //是否导出全部  是：默认一个月  否：查询所有
      type: Boolean,
      required: false,
      default: false,
    },
    isDisableDateRange: {
      //是否设置禁选日期
      type: Boolean,
      required: false,
      default: false,
    },
    allowClear: {
      //是否允许清除
      type: Boolean,
      default: true,
    },
    disabledMonthNum: {
      //禁止选择日期的月数
      type: Number,
      default: 2,
    },
    defaultMonthNum: {
      //展示月数，  默认展示一个月数据（从当前日期往前推一个月）
      type: Number,
      default: 1,
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false,
    },
    // showTime: {
    //   type: Boolean,
    //   required: false,
    //   default: true,
    // },
    defaultValue: {
      type: Array,
      defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
    },
    getCalendarContainer: {
      type: Function,
      default: (node) => node.parentNode,
    },
  },
  data() {
    let that = this
    return {
      dateRange: [],
      defaultValues: [],
      disabledCurrent: null,
      ranges: {
        近一个月: [moment('00:00:00', 'HH:mm:ss').subtract(1, 'months'), moment('23:59:59', 'HH:mm:ss')],
        // 近二个月: [moment('00:00:00', 'HH:mm:ss').subtract(2, 'months'), moment('23:59:59', 'HH:mm:ss')],
        当月: [moment().startOf('month'), moment('23:59:59', 'HH:mm:ss')],
        当天: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
      },
      dataFock: false,
      inputReadOnly: true, //设置输入框为只读
      showTime: {
        format: 'HH:mm:ss',
        defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
      },
    }
  },
  created() {
    this.dateRange = []
      if (this.beginDate && this.endDate) {
        // this.dateRange.push(moment(this.beginDate), moment(this.endDate))
        this.dateRange = [this.beginDate, this.endDate]
      } else {
        //导出全部
        if (this.isExportAll) {
          this.dateRange = []
        } else {
          //默认导出一个月
          const beginDateStr = moment('00:00:00', 'HH:mm:ss')
            .subtract(this.defaultMonthNum, 'months')
            .format('YYYY-MM-DD HH:mm:ss')
          const endDateStr = moment('23:59:59', 'HH:mm:ss').format('YYYY-MM-DD HH:mm:ss')
          // this.dateRange=[moment(beginDateStr),moment(endDateStr)]
          this.dateRange = [beginDateStr, endDateStr]
        }
      }
     
  },
  computed: {
    dateStr() {
      const { beginDate, endDate } = this
      return { beginDate, endDate }
    },
  },
  watch: {
    dateStr: {
      handler(newValue, oldValue) {               
        //  console.log('handler', handler);
        if (newValue.beginDate && newValue.endDate && oldValue.beginDate && oldValue.endDate) {
          if (newValue !== oldValue) {
            const defaultBeginDate = moment('00:00:00', 'HH:mm:ss')
              .subtract(this.defaultMonthNum, 'months')
              .format('YYYY-MM-DD HH:mm:ss')
            const defaultEndDate = moment('12:00:00', 'HH:mm:ss').format('YYYY-MM-DD HH:mm:ss')
            if (newValue.beginDate == defaultBeginDate && newValue.endDate == defaultEndDate) {
              this.disabledCurrent = null
            }
            //this.dateRange=[moment(newValue.beginDate),moment(newValue.endDate)]
            this.dateRange = [newValue.beginDate, newValue.endDate]
          }
        } else { 
          if (newValue.beginDate && newValue.endDate) { 
            this.dateRange = [newValue.beginDate, newValue.endDate]
          }
        }
      },
      deep: true,
    },
  },

  methods: {
    moment,
    //设置禁止选择时间
    disabledDate(current) {
      if (this.isDisableDateRange) {
        if (!this.disabledCurrent) return false
        return (
          current < moment(this.disabledCurrent).subtract(this.disabledMonthNum, 'M') ||
          current > moment(this.disabledCurrent).add(this.disabledMonthNum, 'M').endOf('day')
        )
      } else { 
        return false
      }
    },
    handlePanelChange(value, mode) {},
    //选择日期   待选日期发生变化的回调
    calendarChange(date, dateStrings) {
      this.disabledCurrent = date[0]
      if (date.length == 1) {
        // const defaultBeginDate=moment('00:00:00', 'HH:mm:ss').subtract(this.defaultMonthNum, 'months').format('YYYY-MM-DD HH:mm:ss')
        //   const defaultEndDate=moment('12:00:00','HH:mm:ss').format('YYYY-MM-DD HH:mm:ss')
        if (!this.dataFock) {
          // let beginDateStr=moment(date[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss')
          let beginDateStr = date[0]
          let endDateStr = moment(date[0]).add('month', this.disabledMonthNum).endOf('day').format('YYYY-MM-DD HH:mm:ss')
          //  给结束的日期面板上增加选中
          setTimeout(() => {
            let endDateStrSelect = moment(date[0]).add('month', this.disabledMonthNum).endOf('day').format('YYYY年M月D日')
            let dom = document.querySelectorAll('.ant-calendar-range-right td')
            for (let index = 0; index < dom.length; index++) {
              const element = dom[index]
              let title = element.getAttribute('title')
              if (title === endDateStrSelect) {
                element.click()
                this.dataFock = true
                break
              }
            }
          })
          this.dateRange = [beginDateStr, endDateStr]
        } else {
          this.dateRange = date
        }
      } else {
        const endDate = moment(date[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
        this.dateRange = [date[0], endDate]      
      }
    },
    //选择开始结束日期
    change(date, dateString) {    
      this.dateRange = date
      //this.disabledCurrent=dateString[0]
      this.$emit('update:beginDate', dateString[0])
      this.$emit('update:endDate', dateString[1])
    },
    handleOk(date, dateString) {},
    //打开面板或关闭时时清空禁选日期
    openChange(status) {     
      if (status) {
        this.dataFock = false
        this.disabledCurrent = null
      } else {
        // 当只选了一个日期，关闭面板时，默认起始日期
        if (this.dateRange.length < 2) {
          const beginDateStr = moment('00:00:00', 'HH:mm:ss').subtract(this.defaultMonthNum, 'months').format('YYYY-MM-DD HH:mm:ss')
          const endDateStr = moment('23:59:59', 'HH:mm:ss').format('YYYY-MM-DD HH:mm:ss')
          // this.dateRange=[moment(beginDateStr),moment(endDateStr)]
          this.dateRange = [beginDateStr, endDateStr]
          this.$emit('update:beginDate', beginDateStr)
         this.$emit('update:endDate', endDateStr)
        }
      }
    },
  },
  model: {
    prop: 'value',
    event: 'change',
  },
}
</script>
<style scoped>
/deep/.ant-calendar-picker {
  width: auto !important;
}
</style>